<?php
# Clear everything from the database
# Alias of running clear.sql file manually.
# Clear the thumbnails directorys in the FTP path to prevent thubnails being cached - VERY RISKY if it was defined wrongly
# Disable this in the prodouction mode.

$headers = new headers();
if($headers->is_server())
{
	$messenger = new messenger('error', 'CLEAR - should not run on the live server');
	$headers->back();
}

$sqls=array();
$sqls[]='TRUNCATE gallery_albums;';
$sqls[]='TRUNCATE gallery_albums_sizes;';
$sqls[]='TRUNCATE gallery_images;';
$sqls[]='TRUNCATE gallery_images_albums;';
$sqls[]='TRUNCATE gallery_images_categories;';
$sqls[]='TRUNCATE gallery_images_colors;';
$sqls[]='TRUNCATE gallery_images_sizes;';
$sqls[]='TRUNCATE gallery_images_tags;';
foreach($sqls as $sql)
{
	$db->query($sql);
}

$remove_thumbnails=true; # Very risky | Turn it off
if($remove_thumbnails==true && is_dir(FTPPATH_THUMBNAILS))
{
	if($dh = opendir(FTPPATH_THUMBNAILS))
	{
		while(($file = readdir($dh)) !== false)
		{
			if(in_array($file, array('.', '..'))) continue; # protect some directories
			if('dir'==filetype(FTPPATH_THUMBNAILS.'/'.$file))
			{
				# Recursively remove all those thumbnails directories
				rrmdir(FTPPATH_THUMBNAILS.'/'.$file);
			}
		}
		closedir($dh);
	}
}


/**
* Recursively remove the directories
* First clear all individual files under them
* @link Adapted from user note at - http://php.net/manual/en/function.rmdir.php
*/
function rrmdir($dir='')
{ 
	if(is_dir($dir) && $dir=realpath($dir))
	{ 
		$objects = scandir($dir);
		foreach($objects as $object)
		{
			if($object != '.' && $object != '..')
			{
				$destination = "{$dir}/{$object}";
				if(filetype($destination) == 'dir')
					rrmdir($destination);
				else
					unlink($destination);
			}
		}
		reset($objects);
		rmdir($dir);
	}
}

$messenger = new messenger('notice', 'Everything cleared from the system. Now a fresh new...');
stopper::url('dashboard.php');
?>